var Api = require('../../utils/api.js');

Page({
  data: {
    target: ["增肥", "养生", "减肥"],
    userInfo: {
      target: 0,
      weight: 65,
      height: 168,
      age: 18,
      gender: 1
    }
  },
  onShareAppMessage(o) {

  },
  onShow: function () {
    var that = this
    
    // 检查 openid 是否存在
    let openid = wx.getStorageSync('openid');
    if (!openid) {
      console.warn('openid 未初始化，请重新编译小程序');
      wx.showToast({
        title: '请重新启动小程序',
        icon: 'none',
        duration: 2000
      });
      return;
    }

    wx.request({
      url: Api.userInfo(),
      success(res) {
        console.log(res)
        that.setData({
          userInfo: res.data
        })
      },
      fail(err) {
        console.error('获取用户信息失败:', err);
        // 使用默认数据
        wx.showToast({
          title: '使用默认数据',
          icon: 'none',
          duration: 1500
        });
      }
    })
  },

  // 退出登录
  handleLogout: function() {
    const that = this;
    
    wx.showModal({
      title: '提示',
      content: '确定要退出登录吗？',
      confirmColor: '#39b54a',
      success: function(res) {
        if (res.confirm) {
          // 清除本地存储的登录信息
          wx.removeStorageSync('openid');
          wx.removeStorageSync('userId');
          wx.removeStorageSync('userProfile');
          
          wx.showToast({
            title: '已退出登录',
            icon: 'success',
            duration: 2000
          });
          
          // 延迟跳转到登录页
          setTimeout(function() {
            wx.reLaunch({
              url: '/pages/login/login'
            });
          }, 2000);
        }
      }
    });
  }

})